/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.entity.Caterer;
import model.entity.Items;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.entity.Orders;
import model.entity.PaymentMethod;
import model.entity.Restaurant;

/**
 *
 * @author lnngu_000
 */
public class RestaurantJpaController implements Serializable {

    public RestaurantJpaController(EntityManagerFactory emf) {
        
        this.emf = emf;
    }
    
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Restaurant restaurant) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (restaurant.getItemsCollection() == null) {
            restaurant.setItemsCollection(new ArrayList<Items>());
        }
        if (restaurant.getOrdersCollection() == null) {
            restaurant.setOrdersCollection(new ArrayList<Orders>());
        }
        if (restaurant.getPaymentMethodCollection() == null) {
            restaurant.setPaymentMethodCollection(new ArrayList<PaymentMethod>());
        }
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Caterer catererId = restaurant.getCatererId();
            if (catererId != null) {
                catererId = em.getReference(catererId.getClass(), catererId.getCatererId());
                restaurant.setCatererId(catererId);
            }
            Collection<Items> attachedItemsCollection = new ArrayList<Items>();
            for (Items itemsCollectionItemsToAttach : restaurant.getItemsCollection()) {
                itemsCollectionItemsToAttach = em.getReference(itemsCollectionItemsToAttach.getClass(), itemsCollectionItemsToAttach.getItemId());
                attachedItemsCollection.add(itemsCollectionItemsToAttach);
            }
            restaurant.setItemsCollection(attachedItemsCollection);
            Collection<Orders> attachedOrdersCollection = new ArrayList<Orders>();
            for (Orders ordersCollectionOrdersToAttach : restaurant.getOrdersCollection()) {
                ordersCollectionOrdersToAttach = em.getReference(ordersCollectionOrdersToAttach.getClass(), ordersCollectionOrdersToAttach.getOrderId());
                attachedOrdersCollection.add(ordersCollectionOrdersToAttach);
            }
            restaurant.setOrdersCollection(attachedOrdersCollection);
            Collection<PaymentMethod> attachedPaymentMethodCollection = new ArrayList<PaymentMethod>();
            for (PaymentMethod paymentMethodCollectionPaymentMethodToAttach : restaurant.getPaymentMethodCollection()) {
                paymentMethodCollectionPaymentMethodToAttach = em.getReference(paymentMethodCollectionPaymentMethodToAttach.getClass(), paymentMethodCollectionPaymentMethodToAttach.getPaymentMethodId());
                attachedPaymentMethodCollection.add(paymentMethodCollectionPaymentMethodToAttach);
            }
            restaurant.setPaymentMethodCollection(attachedPaymentMethodCollection);
            em.persist(restaurant);
            if (catererId != null) {
                catererId.getRestaurantCollection().add(restaurant);
                catererId = em.merge(catererId);
            }
            for (Items itemsCollectionItems : restaurant.getItemsCollection()) {
                Restaurant oldRestaurantIdOfItemsCollectionItems = itemsCollectionItems.getRestaurantId();
                itemsCollectionItems.setRestaurantId(restaurant);
                itemsCollectionItems = em.merge(itemsCollectionItems);
                if (oldRestaurantIdOfItemsCollectionItems != null) {
                    oldRestaurantIdOfItemsCollectionItems.getItemsCollection().remove(itemsCollectionItems);
                    oldRestaurantIdOfItemsCollectionItems = em.merge(oldRestaurantIdOfItemsCollectionItems);
                }
            }
            for (Orders ordersCollectionOrders : restaurant.getOrdersCollection()) {
                Restaurant oldRestaurantIdOfOrdersCollectionOrders = ordersCollectionOrders.getRestaurantId();
                ordersCollectionOrders.setRestaurantId(restaurant);
                ordersCollectionOrders = em.merge(ordersCollectionOrders);
                if (oldRestaurantIdOfOrdersCollectionOrders != null) {
                    oldRestaurantIdOfOrdersCollectionOrders.getOrdersCollection().remove(ordersCollectionOrders);
                    oldRestaurantIdOfOrdersCollectionOrders = em.merge(oldRestaurantIdOfOrdersCollectionOrders);
                }
            }
            for (PaymentMethod paymentMethodCollectionPaymentMethod : restaurant.getPaymentMethodCollection()) {
                Restaurant oldRestaurantIdOfPaymentMethodCollectionPaymentMethod = paymentMethodCollectionPaymentMethod.getRestaurantId();
                paymentMethodCollectionPaymentMethod.setRestaurantId(restaurant);
                paymentMethodCollectionPaymentMethod = em.merge(paymentMethodCollectionPaymentMethod);
                if (oldRestaurantIdOfPaymentMethodCollectionPaymentMethod != null) {
                    oldRestaurantIdOfPaymentMethodCollectionPaymentMethod.getPaymentMethodCollection().remove(paymentMethodCollectionPaymentMethod);
                    oldRestaurantIdOfPaymentMethodCollectionPaymentMethod = em.merge(oldRestaurantIdOfPaymentMethodCollectionPaymentMethod);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findRestaurant(restaurant.getRestaurantId()) != null) {
                throw new PreexistingEntityException("Restaurant " + restaurant + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Restaurant restaurant) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Restaurant persistentRestaurant = em.find(Restaurant.class, restaurant.getRestaurantId());
            Caterer catererIdOld = persistentRestaurant.getCatererId();
            Caterer catererIdNew = restaurant.getCatererId();
            Collection<Items> itemsCollectionOld = persistentRestaurant.getItemsCollection();
            Collection<Items> itemsCollectionNew = restaurant.getItemsCollection();
            Collection<Orders> ordersCollectionOld = persistentRestaurant.getOrdersCollection();
            Collection<Orders> ordersCollectionNew = restaurant.getOrdersCollection();
            Collection<PaymentMethod> paymentMethodCollectionOld = persistentRestaurant.getPaymentMethodCollection();
            Collection<PaymentMethod> paymentMethodCollectionNew = restaurant.getPaymentMethodCollection();
            if (catererIdNew != null) {
                catererIdNew = em.getReference(catererIdNew.getClass(), catererIdNew.getCatererId());
                restaurant.setCatererId(catererIdNew);
            }
            Collection<Items> attachedItemsCollectionNew = new ArrayList<Items>();
            for (Items itemsCollectionNewItemsToAttach : itemsCollectionNew) {
                itemsCollectionNewItemsToAttach = em.getReference(itemsCollectionNewItemsToAttach.getClass(), itemsCollectionNewItemsToAttach.getItemId());
                attachedItemsCollectionNew.add(itemsCollectionNewItemsToAttach);
            }
            itemsCollectionNew = attachedItemsCollectionNew;
            restaurant.setItemsCollection(itemsCollectionNew);
            Collection<Orders> attachedOrdersCollectionNew = new ArrayList<Orders>();
            for (Orders ordersCollectionNewOrdersToAttach : ordersCollectionNew) {
                ordersCollectionNewOrdersToAttach = em.getReference(ordersCollectionNewOrdersToAttach.getClass(), ordersCollectionNewOrdersToAttach.getOrderId());
                attachedOrdersCollectionNew.add(ordersCollectionNewOrdersToAttach);
            }
            ordersCollectionNew = attachedOrdersCollectionNew;
            restaurant.setOrdersCollection(ordersCollectionNew);
            Collection<PaymentMethod> attachedPaymentMethodCollectionNew = new ArrayList<PaymentMethod>();
            for (PaymentMethod paymentMethodCollectionNewPaymentMethodToAttach : paymentMethodCollectionNew) {
                paymentMethodCollectionNewPaymentMethodToAttach = em.getReference(paymentMethodCollectionNewPaymentMethodToAttach.getClass(), paymentMethodCollectionNewPaymentMethodToAttach.getPaymentMethodId());
                attachedPaymentMethodCollectionNew.add(paymentMethodCollectionNewPaymentMethodToAttach);
            }
            paymentMethodCollectionNew = attachedPaymentMethodCollectionNew;
            restaurant.setPaymentMethodCollection(paymentMethodCollectionNew);
            restaurant = em.merge(restaurant);
            if (catererIdOld != null && !catererIdOld.equals(catererIdNew)) {
                catererIdOld.getRestaurantCollection().remove(restaurant);
                catererIdOld = em.merge(catererIdOld);
            }
            if (catererIdNew != null && !catererIdNew.equals(catererIdOld)) {
                catererIdNew.getRestaurantCollection().add(restaurant);
                catererIdNew = em.merge(catererIdNew);
            }
            for (Items itemsCollectionOldItems : itemsCollectionOld) {
                if (!itemsCollectionNew.contains(itemsCollectionOldItems)) {
                    itemsCollectionOldItems.setRestaurantId(null);
                    itemsCollectionOldItems = em.merge(itemsCollectionOldItems);
                }
            }
            for (Items itemsCollectionNewItems : itemsCollectionNew) {
                if (!itemsCollectionOld.contains(itemsCollectionNewItems)) {
                    Restaurant oldRestaurantIdOfItemsCollectionNewItems = itemsCollectionNewItems.getRestaurantId();
                    itemsCollectionNewItems.setRestaurantId(restaurant);
                    itemsCollectionNewItems = em.merge(itemsCollectionNewItems);
                    if (oldRestaurantIdOfItemsCollectionNewItems != null && !oldRestaurantIdOfItemsCollectionNewItems.equals(restaurant)) {
                        oldRestaurantIdOfItemsCollectionNewItems.getItemsCollection().remove(itemsCollectionNewItems);
                        oldRestaurantIdOfItemsCollectionNewItems = em.merge(oldRestaurantIdOfItemsCollectionNewItems);
                    }
                }
            }
            for (Orders ordersCollectionOldOrders : ordersCollectionOld) {
                if (!ordersCollectionNew.contains(ordersCollectionOldOrders)) {
                    ordersCollectionOldOrders.setRestaurantId(null);
                    ordersCollectionOldOrders = em.merge(ordersCollectionOldOrders);
                }
            }
            for (Orders ordersCollectionNewOrders : ordersCollectionNew) {
                if (!ordersCollectionOld.contains(ordersCollectionNewOrders)) {
                    Restaurant oldRestaurantIdOfOrdersCollectionNewOrders = ordersCollectionNewOrders.getRestaurantId();
                    ordersCollectionNewOrders.setRestaurantId(restaurant);
                    ordersCollectionNewOrders = em.merge(ordersCollectionNewOrders);
                    if (oldRestaurantIdOfOrdersCollectionNewOrders != null && !oldRestaurantIdOfOrdersCollectionNewOrders.equals(restaurant)) {
                        oldRestaurantIdOfOrdersCollectionNewOrders.getOrdersCollection().remove(ordersCollectionNewOrders);
                        oldRestaurantIdOfOrdersCollectionNewOrders = em.merge(oldRestaurantIdOfOrdersCollectionNewOrders);
                    }
                }
            }
            for (PaymentMethod paymentMethodCollectionOldPaymentMethod : paymentMethodCollectionOld) {
                if (!paymentMethodCollectionNew.contains(paymentMethodCollectionOldPaymentMethod)) {
                    paymentMethodCollectionOldPaymentMethod.setRestaurantId(null);
                    paymentMethodCollectionOldPaymentMethod = em.merge(paymentMethodCollectionOldPaymentMethod);
                }
            }
            for (PaymentMethod paymentMethodCollectionNewPaymentMethod : paymentMethodCollectionNew) {
                if (!paymentMethodCollectionOld.contains(paymentMethodCollectionNewPaymentMethod)) {
                    Restaurant oldRestaurantIdOfPaymentMethodCollectionNewPaymentMethod = paymentMethodCollectionNewPaymentMethod.getRestaurantId();
                    paymentMethodCollectionNewPaymentMethod.setRestaurantId(restaurant);
                    paymentMethodCollectionNewPaymentMethod = em.merge(paymentMethodCollectionNewPaymentMethod);
                    if (oldRestaurantIdOfPaymentMethodCollectionNewPaymentMethod != null && !oldRestaurantIdOfPaymentMethodCollectionNewPaymentMethod.equals(restaurant)) {
                        oldRestaurantIdOfPaymentMethodCollectionNewPaymentMethod.getPaymentMethodCollection().remove(paymentMethodCollectionNewPaymentMethod);
                        oldRestaurantIdOfPaymentMethodCollectionNewPaymentMethod = em.merge(oldRestaurantIdOfPaymentMethodCollectionNewPaymentMethod);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = restaurant.getRestaurantId();
                if (findRestaurant(id) == null) {
                    throw new NonexistentEntityException("The restaurant with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Restaurant restaurant;
            try {
                restaurant = em.getReference(Restaurant.class, id);
                restaurant.getRestaurantId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The restaurant with id " + id + " no longer exists.", enfe);
            }
            Caterer catererId = restaurant.getCatererId();
            if (catererId != null) {
                catererId.getRestaurantCollection().remove(restaurant);
                catererId = em.merge(catererId);
            }
            Collection<Items> itemsCollection = restaurant.getItemsCollection();
            for (Items itemsCollectionItems : itemsCollection) {
                itemsCollectionItems.setRestaurantId(null);
                itemsCollectionItems = em.merge(itemsCollectionItems);
            }
            Collection<Orders> ordersCollection = restaurant.getOrdersCollection();
            for (Orders ordersCollectionOrders : ordersCollection) {
                ordersCollectionOrders.setRestaurantId(null);
                ordersCollectionOrders = em.merge(ordersCollectionOrders);
            }
            Collection<PaymentMethod> paymentMethodCollection = restaurant.getPaymentMethodCollection();
            for (PaymentMethod paymentMethodCollectionPaymentMethod : paymentMethodCollection) {
                paymentMethodCollectionPaymentMethod.setRestaurantId(null);
                paymentMethodCollectionPaymentMethod = em.merge(paymentMethodCollectionPaymentMethod);
            }
            em.remove(restaurant);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Restaurant> findRestaurantEntities() {
        return findRestaurantEntities(true, -1, -1);
    }

    public List<Restaurant> findRestaurantEntities(int maxResults, int firstResult) {
        return findRestaurantEntities(false, maxResults, firstResult);
    }

    private List<Restaurant> findRestaurantEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Restaurant.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Restaurant findRestaurant(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Restaurant.class, id);
        } finally {
            em.close();
        }
    }

    public int getRestaurantCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Restaurant> rt = cq.from(Restaurant.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
